//
//  VarispeedController.m
//  AudioKitOC
//
//  Created by Hwang on 2018/5/8.
//  Copyright © 2018年 AudioKit. All rights reserved.
//

#import "VarispeedController.h"
#import <AVFoundation/AVFoundation.h>

@interface VarispeedController ()

@property (nonatomic, strong) AVAudioEngine *engine;
@property (nonatomic, strong) AVAudioUnitVarispeed *speed;
@property (nonatomic, strong) AVAudioPlayerNode *player;

@end

@implementation VarispeedController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    /*
     由于本机重新采样输入信号，改变播放速率也会改变音高。
     即将速率改变为2.0导致输出音频播放一个八度以上。
      同样将速率改为0.5，可以使输出音频降低一个八度。
      播放速率和音调可以按照
      rate = pow（2，分/ 1200.0）
      以美分为单位 = 1200.0 * log2（比率）
     
     rate  = pow(2, cents/1200.0)
     pitch in cents  = 1200.0 * log2(rate)
     rate defaul = 1;
     */
    _speed = [[AVAudioUnitVarispeed alloc] init];
    _player = [[AVAudioPlayerNode alloc] init];
    
    NSURL *drumLoopURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"追光者" ofType:@"mp3"]];
    AVAudioFile *drumLoopFile = [[AVAudioFile alloc] initForReading:drumLoopURL error:nil];
    AVAudioPCMBuffer *_playerLoopBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:[drumLoopFile processingFormat] frameCapacity:(AVAudioFrameCount)[drumLoopFile length]];
    BOOL success = [drumLoopFile readIntoBuffer:_playerLoopBuffer error:nil];
    if (success) {
        NSLog(@"success");
    }
    
    _engine = [[AVAudioEngine alloc] init];
    
    [_engine attachNode:_player];
    [_engine attachNode:_speed];
    [_engine connect:_player to:_speed format:_playerLoopBuffer.format];
    [_engine connect:_speed to:_engine.mainMixerNode format:_playerLoopBuffer.format];
    
    NSError *error;
    BOOL startSuccess = [_engine startAndReturnError:&error];
    if (startSuccess) {
        NSLog(@"startSuccess");
    } else {
        NSLog(@"%@", error.description);
    }
    [_player scheduleBuffer:_playerLoopBuffer completionHandler:nil];
    [_player play];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


- (IBAction)rate:(UISlider *)sender {
    _speed.rate = sender.value;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
